package com.yh.serviceimpl;

import com.yh.dao.RoleDao;
import com.yh.dao.UsersDao;
import com.yh.javabean.Role;
import com.yh.javabean.Users;
import com.yh.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service("usersService")
public class UsersServiceImpl implements UsersService {

    @Autowired
    UsersDao usersDao;
    @Autowired
    RoleDao roleDao;



    //如果没有查询到对应数据 返回null(最好手动抛出异常)
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询数据返回实体类对应数据
        Users users = usersDao.selectByUserName(username);
        if(users!=null){

            User user = new User(users.getUsername(),
                    "{noop}"+users.getPassword(),
                    users.getStatus() != 0 ,
                    true,true,true,
                    getAuthority(users.getId()));
            return user;
        }else {
            throw new UsernameNotFoundException("账号不存在");
        }
    }

    //默认users中没有任何权限 无法登录

    public Set<GrantedAuthority> getAuthority(int uid){
        Set<GrantedAuthority> simpleGrantedAuthorities = new HashSet<>();
        Role role = roleDao.selectByUid(uid);

        simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        return  simpleGrantedAuthorities;
    }


}
